package com.hyh.eblog.controller;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hyh.eblog.common.lang.Result;
import com.hyh.eblog.entity.Post;
import com.hyh.eblog.util.ValidationUtil;
import com.hyh.eblog.vo.CommentVo;
import com.hyh.eblog.vo.PostVo;
import org.apache.logging.log4j.message.ReusableMessage;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Summerday
 * @since 2020-10-19
 */
@Controller
public class PostController extends BaseController {
    @GetMapping("/category/{id:\\d*}")
    public String category(@PathVariable("id") Long id) {
        int pn = ServletRequestUtils.getIntParameter(request, "pn", 1);
        request.setAttribute("currId", id);
        request.setAttribute("pn", pn);
        return "post/category";
    }

    @GetMapping("/post/{id:\\d*}")
    public String detail(@PathVariable("id") Long id) {
        PostVo postVo = postService.selectOnePost(
                new QueryWrapper<Post>().eq("p.id", id)
        );
        Assert.notNull(postVo, "文章已被删除");

        postService.setViewCount(postVo);

        //分页 文章id 用户id 排序
        IPage<CommentVo> results = commentService.paging(getPage(), postVo.getId(), null, "created");
        request.setAttribute("currCategoryId", postVo.getCategoryId());
        request.setAttribute("post", postVo);
        request.setAttribute("pageData", results);
        return "post/detail";
    }

    @GetMapping("/post/edit")
    public String edit() {
        String id = request.getParameter("id");
        if (!StringUtils.isEmpty(id)) {
            Post post = postService.getById(id);
            Assert.isTrue(post != null, "该帖子已被删除");
            Assert.isTrue(post.getUserId().longValue() == getProfileId().longValue(), "没权限操作该文章");
            request.setAttribute("post",post);
        }
        request.setAttribute("categories",categoryService.list());
        return "/post/edit";
    }

    @ResponseBody
    @PostMapping("/post/submit")
    public Result submit(Post post){
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(post);
        if(validResult.hasErrors()){
            return Result.fail(validResult.getErrors());
        }
        if(post.getId() == null){
            post.setUserId(getProfileId());
            post.setCommentCount(0);
            post.setEditMode(null);
            post.setLevel(0);
            post.setRecommend(false);
            post.setViewCount(0);
            post.setVoteDown(0);
            post.setVoteUp(0);
            postService.save(post);
        }else {
            Post tempPost = postService.getById(post.getId());
            Assert.isTrue(tempPost.getUserId().longValue() == getProfileId().longValue(), "无权限编辑此文章！");

            tempPost.setTitle(post.getTitle());
            tempPost.setContent(post.getContent());
            tempPost.setCategoryId(post.getCategoryId());
            postService.updateById(tempPost);
        }
        return Result.success().action("/post/" + post.getId());
    }

    @ResponseBody
    @PostMapping("/post/delete")
    public Result deleteById(Long id){
        Post post = postService.getById(id);
        Assert.notNull(post,"该帖子已被删除");
        Assert.isTrue(post.getUserId().longValue() == getProfileId().longValue(),"无权限删除此文章");
        postService.removeById(id);

        //删除相关消息,收藏等
        userMessageService.removeByMap(MapUtil.of("post_id",id));
        userCollectionService.removeByMap(MapUtil.of("post_id",id));

        return Result.success("操作成功");
    }


}
